from django.shortcuts import redirect, render
from django.urls.base import reverse
from django.core.paginator import Paginator
from goods.models import GoodsType, IndexGoodsBanner, IndexPromotionBanner, IndexTypeGoodsBanner, GoodsSKU, Goods
from order.models import OrderGoods
from django_redis import get_redis_connection
from django.core.cache import cache
# Create your views here.

def index(request):

    # 尝试从内存获取信息
    context = cache.get('index_data')
    # 如果没有就去查询数据库
    if context is None:
        # 获取商品的种类信息
        types = GoodsType.objects.all()

        # 获取首页轮播商品信息 
        goods_banners = IndexGoodsBanner.objects.all().order_by('index')

        # 获取首页促销活动信息
        promotion_banners = IndexPromotionBanner.objects.all().order_by('index')

        # 获取首页分类商品展示信息
        for type in types:
            picture_banners = IndexTypeGoodsBanner.objects.filter(
                type=type, display_type=1).order_by('index')
            # 获取type种类首页展示的文字信息
            title_banners = IndexTypeGoodsBanner.objects.filter(
                type=type, display_type=0).order_by('index')

            # 动态给type增加属性
            type.title_banners = title_banners
            type.picture_banners = picture_banners

        context = {
            'types': types,
            'goods_banners': goods_banners,
            'promotion_banners': promotion_banners,
            'cart_count': 0
        }

        cache.set('index_data', context, 3600)

    # 获取用户购物车中商品的数目
    user = request.user
    cart_count = 0
    if user.is_authenticated:
        # 用户已经登录
        conn = get_redis_connection('history')
        cart_key = 'cart_%d' % user.id
        cart_count = conn.hlen(cart_key)

    # 组织模板上下文
    context.update(cart_count=cart_count)

    return render(request, 'goods/index.html', context=context)


def goods(request, goods_id):

    # 查询产品数据
    # 产品sku
    try:
        good = GoodsSKU.objects.get(id=goods_id)
    except:
        # 如果不存在就跳转到首页
        return redirect(reverse('goods:index'))
    # 首先获取类型
    types = GoodsType.objects.all()
    # 产品类型里面的其他产品
    good_relative = GoodsSKU.objects.filter(
        type=good.type).order_by('-create_time')[:2]
    # 获取产品spu
    other_spu = GoodsSKU.objects.filter(goods=good.goods).exclude(id=good.id)

    # 获取评论   把空的排除
    comments = OrderGoods.objects.filter(sku = good).exclude(comment='').order_by('-update_time')

    context = {'cart_count': 0, 'good': good,'types':types,
               'good_relative': good_relative, 'other_spu': other_spu,'comments':comments}

    # 获取用户购物车中商品的数目
    user = request.user
    if user.is_authenticated:
        # 用户已经登录
        conn = get_redis_connection('history')
        cart_key = 'cart_%d' % user.id
        cart_count = conn.hlen(cart_key)
        context.update(cart_count=cart_count)

        # 用户登录并浏览商品我们做记录
        conn = get_redis_connection('history')
        history_key = 'history_%s'%user.id
        # 移出列表中已经存在的
        conn.lrem(history_key,0,goods_id)
        # 把新的添加到左侧
        conn.lpush(history_key,goods_id)
        # 一个用户最多保存5个，所以把多余的删掉
        conn.ltrim(history_key,0,4)

    return render(request, 'goods/goods.html', context)


def list(request,type,page):
    # 获取是什么类型
    try:
        good_type = GoodsType.objects.get(id=type)
    except:
        return render(reverse('goods:index'))
    # 首先获取全部类型 页头导航需要
    types = GoodsType.objects.all()
    # 按照得到的类型得到相关的最新的两条数据
    good_relative = GoodsSKU.objects.filter(type=good_type).order_by('-create_time')[:2]
    # 获取此类所有的商品
    # 根据传的sort参数判断要以那个方式排序
    sort = request.GET.get('sort')
    if sort == 'price':
        goods = GoodsSKU.objects.filter(type=good_type).order_by('-price')
    elif sort == 'sales':
        goods = GoodsSKU.objects.filter(type=good_type).order_by('-sales')
    else:
        sort = 'default'
        # 默认就按照id排序
        goods = GoodsSKU.objects.filter(type=good_type).order_by('-id')

    paginator = Paginator(goods,1)
    try:
        page = int(page)
    except:
        page = 1

    if page > paginator.num_pages:
        page = 1
    
    # 控制页面上显示的页码 最多显示5个
    # 如果页码不够5那么显示的就是12345
    # 如果当前页码是前三页显示的也是12345
    # 如果当前页是最后3页 显示最后5页
    # 其他情况当前页，前两页，后两页
    num_pages = paginator.num_pages
    if num_pages<5:
        pages = range(1,num_pages+1)
    elif page <=3:
        pages = range(1,6)
    elif num_pages - page <= 2:
        pages = range(num_pages-4, num_pages+1)
    else:
        pages = range(page-2,page+3)

    goods_page = paginator.page(page)

    context = {'good_relative':good_relative,'types':types,'good_type':good_type,'goods':goods_page,'sort':sort,'pages':pages}
    # 获取用户购物车中商品的数目
    user = request.user
    if user.is_authenticated:
        # 用户已经登录
        conn = get_redis_connection('history')
        cart_key = 'cart_%d' % user.id
        cart_count = conn.hlen(cart_key)
        context.update(cart_count=cart_count)
    return render(request, 'goods/list.html',context=context)